package com.example.a2032.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.a2032.R;
import com.example.a2032.db.DataDbHelper;
import com.example.a2032.db.dao.PPGDataDao;
import com.example.a2032.db.dao.RealTimeStepDao;
import com.example.a2032.entity.PPGMeasureData;
import com.example.a2032.livedatas.LiveDataBus;
import com.example.a2032.livedatas.SingleSourceLiveData;
import com.example.a2032.entity.RealTimeData;
import com.hyphenate.chat.EMClient;

public class RealTimeStepViewModel extends AndroidViewModel {

    private final SingleSourceLiveData<RealTimeData> realTimeStepObservable;
    private final SingleSourceLiveData<PPGMeasureData> heartRateObservable;
    private MutableLiveData<String> homeUnReadObservable;
    RealTimeStepDao realTimeStepDao;
    PPGDataDao heartRateDataDao;
    Application application;

    public RealTimeStepViewModel(@NonNull Application application) {
        super(application);
        this.application = application;
        realTimeStepDao = DataDbHelper.getInstance(application).getRealTimeStepDao();
        heartRateDataDao = DataDbHelper.getInstance(application).getPPGDataDao();
        realTimeStepObservable = new SingleSourceLiveData<>();
        heartRateObservable = new SingleSourceLiveData<>();
        homeUnReadObservable = new MutableLiveData<>();
    }

    public LiveData<String> homeUnReadObservable() {
        return homeUnReadObservable;
    }

    public LiveData<RealTimeData> getLastRealTime(String date) {
        realTimeStepObservable.setSource(realTimeStepDao.loadLastRealTimeStep(date));
        return realTimeStepObservable;
    }

    public LiveData<PPGMeasureData> getLastHeartRate() {
        heartRateObservable.setSource(heartRateDataDao.getLastPPGData(PPGMeasureData.MeasureData_PPGHR));
        return heartRateObservable;
    }

    public LiveDataBus messageChangeObservable() {
        return LiveDataBus.get();
    }

    public void checkUnreadMsg() {
        int unreadCount = 0;
        int unreadMessageCount = EMClient.getInstance().chatManager().getUnreadMessageCount();
        String count = getUnreadCount(unreadCount + unreadMessageCount);
        homeUnReadObservable.postValue(count);
    }

    private String getUnreadCount(int count) {
        if (count <= 0) {
            count = 0;
        }
        if (count > 99) {
            return "99+ ";
        }
        return count + " ";
    }
}
